<template>
  <div class="group-list-container">
    <el-input
      v-model="searchText"
      placeholder="请输入发布人姓名"
      clearable
      :prefix-icon="Search"
      class="group-search"
    />

    <el-button type="primary" :icon="Plus" class="add-button" @click="handleAddGroup">
      添加发布人
    </el-button>

    <div class="group-list">
      <div
        v-for="(group, index) in filteredGroups"
        :key="index"
        :class="['group-item', { active: activeGroup === group.id }]"
        @click="handleClick(group)"
        @mouseenter="hoverIndex = index"
        @mouseleave="hoverIndex = -1"
      >
        <div class="name">
          <img :src="group.avatarUrl" class="material-icon" />
          <span>{{ group.name }}</span>
        </div>
        <div class="opera" v-show="hoverIndex === index">
          <i class="iconfont-sys edit-icon" @click.stop="handleEdit(group)">&#xe65f;</i>
          <i class="iconfont-sys del-icon" @click.stop="deleteGroup(group)">&#xe783;</i>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="showPublisherDialog"
      :title="editData.id ? '编辑发布人' : '新增发布人'"
      @close="showPublisherDialog = false"
      :close-on-click-modal="false"
      width="600"
    >
      <template #default>
        <el-form
          ref="formRef"
          :model="form"
          :rules="formRule"
          label-position="right"
          label-width="auto"
        >
          <el-form-item label="发布人名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="avatarUrl">
            <div class="avatar-uploader" @click="showImageChooseDialog = true">
              <el-image
                v-if="form.avatarUrl"
                :src="form.avatarUrl"
                class="avatar"
                fit="contain"
              ></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"
                ><el-icon> <Plus /> </el-icon
              ></i>
              <div v-if="form.avatarUrl" class="mask">替换</div>
              <el-icon
                v-if="form.avatarUrl"
                class="del-image"
                :size="20"
                @click.stop="handleDelImg"
              >
                <CircleCloseFilled />
              </el-icon>
            </div>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio :value="0">男</el-radio>
              <el-radio :value="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="简介" prop="introduction">
            <el-input type="textarea" v-model="form.introduction" :rows="8"></el-input>
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <el-button @click="showPublisherDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit(formRef)"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <image-selected-dialog
      v-if="showImageChooseDialog"
      :single-type="true"
      :show-image-choose-dialog="showImageChooseDialog"
      @close-dialog="handleCloseImageDialog"
      :operationType="false"
    ></image-selected-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { Search, Plus } from '@element-plus/icons-vue'
  import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
  import cloneDeep from 'lodash/cloneDeep'
  import { FormInstance, FormRules } from 'element-plus'
  import { addCreator, updateCreator, delCreator } from '@/api/marketing'

  interface GroupItem {
    id: string
    name: string
    introduction: string
    gender: number
    avatarUrl: string
    [key: string]: any
  }

  const props = defineProps<{
    publisherGroup: GroupItem[]
    defaultGroup: string
  }>()

  const emit = defineEmits(['updatePublisherGroup', 'selectPublisher'])

  const form = reactive({
    name: '',
    introduction: '',
    gender: 0,
    avatarUrl: ''
  })

  const formRef = ref<FormInstance>()

  const formRule = reactive<FormRules>({
    name: [{ required: true, message: '请输入发布人名称', trigger: 'blur' }],
    avatarUrl: [{ required: true, message: '请选择头像', trigger: 'change' }],
    gender: [{ required: true, message: '请选择', trigger: 'change' }],
    introduction: [{ required: true, message: '请输入简介', trigger: 'blur' }]
  })

  const searchText = ref('')
  const activeGroup = ref('')
  const hoverIndex = ref(-1)
  const showImageChooseDialog = ref(false)
  const showPublisherDialog = ref(false)
  const editData = ref<any>({})
  const submitLoading = ref(false)

  const filteredGroups = computed(() => {
    if (!searchText.value) return props.publisherGroup
    return props.publisherGroup.filter((group) => group.name.includes(searchText.value))
  })

  function handleAddGroup() {
    form.name = ''
    form.introduction = ''
    form.gender = 0
    form.avatarUrl = ''
    showPublisherDialog.value = true
  }

  function handleClick(group: any) {
    activeGroup.value = group.id
    emit('selectPublisher', group)
  }

  function handleEdit(groupData: any) {
    editData.value = cloneDeep(groupData)
    form.name = editData.value.name
    form.gender = editData.value.gender
    form.avatarUrl = editData.value.avatarUrl
    form.introduction = editData.value.introduction
    showPublisherDialog.value = true
  }

  const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        if (editData.value.id) {
          handleEditPublisher()
        } else {
          handleAddPublisher()
        }
      }
    })
  }

  function deleteGroup(group: any) {
    ElMessageBox.confirm('确定要删除吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(() => {
      delPublisher(group)
    })
  }

  async function delPublisher(group: any) {
    const res = await delCreator(group.id)
    if (res.code === '00000') {
      updatePublisher()
      ElMessage.success('删除成功')
    }
  }

  function handleCloseImageDialog(val: any) {
    if (val) {
      form.avatarUrl = val.fileUrl
    }
    showImageChooseDialog.value = false
  }

  function handleDelImg() {
    form.avatarUrl = ''
  }

  async function handleAddPublisher() {
    try {
      submitLoading.value = true
      const res = await addCreator(form)
      if (res.code === '00000') {
        updatePublisher()
        ElMessage.success('新增成功')
        showPublisherDialog.value = false
      }
    } catch {
    } finally {
      submitLoading.value = false
    }
  }

  async function handleEditPublisher() {
    try {
      submitLoading.value = true
      const res = await updateCreator(editData.value.id, form)
      if (res.code === '00000') {
        updatePublisher()
        ElMessage.success('编辑成功')
        showPublisherDialog.value = false
      }
    } catch {
    } finally {
      submitLoading.value = false
    }
  }

  function updatePublisher() {
    emit('updatePublisherGroup')
  }

  onMounted(() => {
    activeGroup.value = props.defaultGroup
  })
</script>

<style scoped lang="scss">
  .group-list-container {
    width: 220px;
    padding: 12px;
    border-right: 1px solid #eee;
    position: relative;
    background: #fff;
  }

  .group-search {
    width: 100%;
    margin-bottom: 10px;
  }

  .add-button {
    width: 100%;
    margin-bottom: 16px;
  }

  .group-list {
    border-top: 1px solid #f0f0f0;
  }

  .group-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 10px;
    font-size: 14px;
    cursor: pointer;
    transition: background 0.2s;

    .name {
      display: flex;
      align-items: center;

      .material-icon {
        width: 18px;
        height: 18px;
        margin-right: 5px;
      }
    }
  }

  .group-item:hover {
    background-color: #eff8ec;

    .count {
      display: none;
    }

    .opera {
      display: block;
    }
  }

  .group-item.active {
    color: var(--el-color-primary);
    background-color: #eff8ec;
    border-right: 2px solid var(--el-color-primary);
  }

  .group-item .count {
    color: #999;
    font-size: 13px;
  }

  .opera {
    display: none;

    .edit-icon {
      color: var(--el-color-primary);
      margin-right: 6px;
    }

    .del-icon {
      color: #f34965;
    }
  }

  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;

    .mask {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 24px;
      background-color: rgba(0, 0, 0, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s ease;
      color: #fff;
      font-size: 12px;
    }

    .del-image {
      display: none;
      position: absolute;
      top: 0;
      right: 0;
      cursor: pointer;
      color: #8c939d;
    }

    &:hover .mask {
      opacity: 1;
    }

    &:hover .del-image {
      display: block;
    }
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
</style>
